package com.hlhj.carview.aty

import android.Manifest
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.view.WindowManager
import com.hlhj.carview.BaseAty
import com.hlhj.carview.Constant
import com.hlhj.carview.Iview.LoginView
import com.hlhj.carview.R
import com.hlhj.carview.Toast
import com.hlhj.carview.bean.LoginBean
import com.hlhj.carview.bean.MyBaseBean
import com.hlhj.carview.customView.DilaogPrivacy
import com.hlhj.carview.http.Apis
import com.hlhj.carview.http.CustomAction
import com.hlhj.carview.http.Urls
import com.hlhj.carview.presenter.LoginPresenter
import com.hlhj.carview.utils.SPHelper
import com.hlhj.carview.utils.ToastUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpHeaders
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.aty_login.*

/**
 * Created by Never Fear   on 2018\12\18 0018.
Never More....
 *Dirty
 */
class LoginAty :BaseAty<LoginView,LoginPresenter>(), LoginView {

    companion object{
        var phoneNum:String=""
    }
    private var sec=60
    private var fSec=60
    private val smsHandler=object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            sec--
            if (sec<1){
                sec=60
                btSendSms.isClickable=true
                btSendSms.text=getString(R.string.sendSms)
            }else{
                this.sendEmptyMessageDelayed(1,1000)
                btSendSms.isClickable=false
                btSendSms.setText("${sec}秒")
            }
        }
    }
    private val forgetHandler=object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            fSec--
            if (fSec<1){
                fSec=60
                btSendSmsForget.isClickable=true
                btSendSmsForget.text=getString(R.string.sendSms)
            }else{
                this.sendEmptyMessageDelayed(1,1000)
                btSendSmsForget.isClickable=false
                btSendSmsForget.setText("${sec}秒")
            }
        }
    }
    override fun sendSmsResp(myBaseBean: MyBaseBean) {
        ToastUtil.toast(getString(R.string.code_send_sucess),this)
        smsHandler?.sendEmptyMessage(1)
        forgetHandler?.sendEmptyMessage(1)
    }


    override fun loginResp(loginBean: LoginBean) {
        SPHelper.saveToken(loginBean.info.token.access_token,this)

        val headers = HttpHeaders()
        headers.put("Authorization","Bearer ${SPHelper.getToken(this)}")
        OkGo.getInstance().addCommonHeaders(headers)

        SPHelper.saveLogin(true,this)
        Constant.name=loginBean.info.member.name
        SPHelper.saveHead(Urls.Img+loginBean.info.member.head_img,this)
        val intent = Intent(this, MainActivity::class.java)
        intent.putExtra("head",loginBean.info.member.head_img)
        startActivity(intent)
        finish()
    }

    override fun loginFailed(msg: String) {
        tvErro.text=msg
    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        super.onDestroy()
        smsHandler?.removeMessages(1)
        forgetHandler?.removeMessages(1)
    }
    override fun regisResp(myBaseBean: MyBaseBean) {
        ToastUtil.toast(getString(R.string.regis_success),this)
        phoneRegis.setText("")
        codeRegis.setText("")
        pwdRegis.setText("")
        pwdRegisAgain.setText("")

        btBack2.performClick()
    }

    override fun changePwdResp(myBaseBean: MyBaseBean) {
        ToastUtil.toast(getString(R.string.change_pwd_success),this)
        phoneForget.setText("")
        codeForget.setText("")
        newPwd.setText("")
        newPwdAg.setText("")
        fSec=1
        btBack1.performClick()
    }

    override fun initView() {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        if (RxPermissions.getInstance(this).isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)){

        }else{
            RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION)
                    .subscribe {
                        b->

                    }
        }

    }

    override fun logicStart() {
        if (SPHelper.getLogin(this)){
            startActivity(Intent(this,MainActivity::class.java))
        }
    }

    override fun setListener() {
        btCommitForget.setOnClickListener {
            if (phoneForget.text.isEmpty()){
                ToastUtil.toast(getString(R.string.nullphone),this)
                return@setOnClickListener
            }
            if (codeForget.text.isEmpty()){
                ToastUtil.toast(getString(R.string.code_not_right),this)
                return@setOnClickListener
            }
            if (newPwd.text.isEmpty()||newPwdAg.text.isEmpty()){
                ToastUtil.toast(getString(R.string.pwd_not_null),this)
                return@setOnClickListener
            }
            if (!newPwdAg.text.toString().equals(newPwd.text.toString())){
                ToastUtil.toast(getString(R.string.pwds_not_same),this)
            }
            presenter?.changePwd(phoneForget.text.toString(),codeForget.text.toString(),newPwd.text.toString(),newPwdAg.text.toString(),this)
        }
        btSendSmsForget.setOnClickListener {
            if (phoneForget.text.isEmpty()){
                ToastUtil.toast(getString(R.string.nullphone),this)
                return@setOnClickListener
            }
            presenter?.sendSms(phoneForget.text.toString(),this)
        }
        btSendSms.setOnClickListener {
            if (phoneRegis.text.isEmpty()){
                ToastUtil.toast(getString(R.string.nullphone),this)
                return@setOnClickListener
            }
            presenter?.sendSms(phoneRegis.text.toString(),this)
        }
        btRegisCommit.setOnClickListener {
            if (phoneRegis.text.isEmpty()){
                ToastUtil.toast(getString(R.string.nullphone),this)
                return@setOnClickListener
            }
            if (pwdRegis.text.isEmpty()||pwdRegisAgain.text.isEmpty()){
                ToastUtil.toast(getString(R.string.pwd_not_null),this)
                return@setOnClickListener
            }
            if (!pwdRegis.text.toString().equals(pwdRegisAgain.text.toString())){
                ToastUtil.toast(getString(R.string.pwds_not_same),this)
                return@setOnClickListener
            }
            if (isConfirm.isChecked==false){
                ToastUtil.toast("请同意用户服务协议",this)
                return@setOnClickListener
            }
            Apis.newRegis(phoneRegis.text.toString(),pwdRegis.text.toString())
                    ?.let {
                        it.subscribe(object :CustomAction<Response<MyBaseBean>>(this){
                            override fun httpSuccess(t: Response<MyBaseBean>) {
                                "注册成功".Toast()
                                SPHelper.saveToken(phoneRegis.text.toString(),this@LoginAty)
                                SPHelper.saveLogin(true,this@LoginAty)
                               val i= Intent(this@LoginAty,MainActivity::class.java)
                                startActivity(i)
                                finish()
                            }
                        })
                    }
//            presenter?.regis(phoneRegis.text.toString(),codeRegis.text.toString(),pwdRegis.text.toString(),pwdRegisAgain.text.toString(),this)

        }
        btLogin.setOnClickListener {
            Apis.newLogin(phoneLogin.text.toString(),pwdLogin.text.toString())
                    ?.let {
                        it.subscribe(object :CustomAction<Response<MyBaseBean>>(this){
                            override fun httpSuccess(t: Response<MyBaseBean>) {
                                "登录成功".Toast()
                                SPHelper.saveToken(phoneLogin.text.toString(),this@LoginAty)
                                SPHelper.saveLogin(true,this@LoginAty)
                                val intent = Intent(this@LoginAty, MainActivity::class.java)
                                startActivity(intent)
                                finish()
                            }

                            override fun httpFailed(e: Throwable?) {
                                super.httpFailed(e)
                                "用户名或密码不正确，请重新输入".Toast()

                            }

                        })
                    }

        }
        btRegis.setOnClickListener {
            val animator = ObjectAnimator.ofFloat(loRegis, "translationX", 2000f, 0f)
            animator.duration=800
            animator.start()

            val animator2 = ObjectAnimator.ofFloat(loLogin, "translationX", 0f, -2000f)
            animator2.duration=800
            animator2.start()
        }

        btForget.setOnClickListener {
            val animator = ObjectAnimator.ofFloat(loForget, "translationX", -2000f, 0f)
            animator.duration=800
            animator.start()

            val animator2 = ObjectAnimator.ofFloat(loLogin, "translationX", 0f, 2000f)
            animator2.duration=800
            animator2.start()
        }

        btBack1.setOnClickListener {
            val animator = ObjectAnimator.ofFloat(loForget, "translationX", 0f, -2000f)
            animator.duration=800
            animator.start()

            val animator2 = ObjectAnimator.ofFloat(loLogin, "translationX", 2000f, 0f)
            animator2.duration=800
            animator2.start()
        }

        btBack2.setOnClickListener {
            val animator = ObjectAnimator.ofFloat(loRegis, "translationX", 0f, 2000f)
            animator.duration=800
            animator.start()

            val animator2 = ObjectAnimator.ofFloat(loLogin, "translationX", -2000f, 0f)
            animator2.duration=800
            animator2.start()
        }
        btPrivacy.setOnClickListener {
            DilaogPrivacy(this).show()
        }
    }

    override fun bindView(): LoginView {
        return this
    }

    override fun createPresenter(): LoginPresenter {
        return LoginPresenter()
    }

    override fun getContentID(): Int {
        return R.layout.aty_login
    }
}